import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/material.dart' show DataCell, DataColumn;
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

import '../../components/buttons.dart';
import '../../components/data_table.dart';
import '../../model/school_grade_subject_model.dart';
import '../../utils/date_utils.dart';
import '../app/app_dict_data.dart';
import 'school_grade_subject_view_edit.dart';
import 'school_grade_subject_view_model.dart';

//学校:年级学科列表
class SchoolGradeSubjectViewList extends StatefulWidget {
  final String schoolId;

  const SchoolGradeSubjectViewList({super.key, required this.schoolId});

  @override
  State<SchoolGradeSubjectViewList> createState() =>
      _SchoolGradeSubjectViewListState();
}

class _SchoolGradeSubjectViewListState
    extends State<SchoolGradeSubjectViewList> {
  final queryFormKey = GlobalKey<FormState>();
  final tableKey = GlobalKey<DataTableState<SchoolGradeSubjectItemRes>>();

  @override
  void initState() {
    super.initState();
    //加载数据
    final model = context.read<SchoolGradeSubjectViewModel>();
    model.loadInit(widget.schoolId, afterHandler: () => query(model));
  }

  void query(final SchoolGradeSubjectViewModel model) =>
      model.query(widget.schoolId);

  Widget buildQueryForm(final SchoolGradeSubjectViewModel model) {
    Widget buildField(SchoolGradeSubjectQueryField field,
        Widget Function(TextEditingController? c, String label) handler) {
      final label = field.label;
      final controller = model.getController(field);
      return SizedBox(
        width: 128.w,
        child: InfoLabel(label: label, child: handler(controller, label)),
      );
    }

    return Form(
      key: queryFormKey,
      child: Wrap(
        spacing: 5.w,
        children: [
          //学年学期
          buildField(
            SchoolGradeSubjectQueryField.semester,
            (c, label) => ComboboxFormField(
              placeholder: Text(label),
              items: model.semestersBySchool(widget.schoolId),
              onChanged: (val) => c?.text = val ?? '',
            ),
          ),
          //年级
          buildField(
            SchoolGradeSubjectQueryField.grade,
            (c, label) => ComboboxFormField(
              placeholder: Text(label),
              items: model.gradesBySchool(widget.schoolId),
              onChanged: (val) => c?.text = val ?? '',
            ),
          ),
          //状态
          buildField(
            SchoolGradeSubjectQueryField.status,
            (ctr, label) => ComboboxFormField(
              placeholder: Text(label),
              items: model.statusOpts,
              onChanged: (val) => ctr?.text = val ?? "1",
            ),
          ),
        ],
      ),
    );
  }

  Widget buildQueryBars(final SchoolGradeSubjectViewModel model) => Wrap(
        spacing: 2.w,
        children: [
          //查询
          buttons.query(onPressed: () => query(model)),
          //重置
          buttons.reset(onPressed: () {
            queryFormKey.currentState?.reset();
            model.cleanQueryFields();
            query(model);
          }),
          //新增
          buttons.add(onPressed: () => editHandler(model, null)),
        ],
      );

  void editHandler(SchoolGradeSubjectViewModel model, String? id) async {
    final isAdd = (id ?? '').isEmpty;
    final ret = await showDialog<bool>(
      context: context,
      builder: (context) {
        final size = MediaQuery.sizeOf(context);
        final padding = PageHeader.horizontalPadding(context);
        return ContentDialog(
          title: Text('${isAdd ? '新增' : '编辑'}年级科目'),
          constraints: BoxConstraints(
            maxWidth: size.width - padding * 2,
            maxHeight: size.height - padding * 2,
          ),
          content: ChangeNotifierProvider.value(
            value: model,
            builder: (_, __) => SchoolGradeSubjectViewEdit(
              schoolId: widget.schoolId,
              id: id,
            ),
          ),
        );
      },
    );
    //关闭弹框
    if (ret ?? false) {
      //重新加载
      query(model);
    }
  }

  @override
  Widget build(final BuildContext context) =>
      Consumer<SchoolGradeSubjectViewModel>(
        builder: (context, model, _) => ScaffoldPage.scrollable(
          header: Column(children: [
            PageHeader(title: const Text('年级科目')),
            Padding(
              padding: () {
                final padding = PageHeader.horizontalPadding(context);
                return EdgeInsetsDirectional.symmetric(horizontal: padding);
              }(),
              child: Row(children: [
                //查询条件
                buildQueryForm(model),
                //占位
                Expanded(child: Container()),
                //查询按钮
                buildQueryBars(model),
              ]),
            ),
            SizedBox(height: 15.h),
          ]),
          children: [buildTable(model)],
        ),
      );

  Widget buildTable(final SchoolGradeSubjectViewModel model) {
    final labels = <String>[
      '学年学期',
      '年级',
      '科目',
      '分值',
      '折算分',
      '状态',
      '创建时间',
      '操作'
    ];
    Text buildText(final String label) => Text(
          label,
          softWrap: false,
          overflow: TextOverflow.ellipsis,
        );
    DataCell buildCell(String? Function() handler) =>
        DataCell(buildText(handler.call() ?? ''));
    final dtFormat = 'yyyy-MM-dd HH:mm:ss';
    return DataTable<SchoolGradeSubjectItemRes>(
      key: tableKey,
      model: model.queryModel,
      columns: labels.map((e) => DataColumn(label: Text(e))).toList(),
      onLoadData: () => query(model),
      onRowCallback: (row) => [
        //学年学期
        buildCell(
          () => model.getSemesterTitle(
            widget.schoolId,
            row.semesterId,
          ),
        ),
        //年级
        buildCell(() => model.getGradeTitle(widget.schoolId, row.gradeVal)),
        //科目
        buildCell(() => appDictData.getLabel('subject', row.subjectVal)),
        //默认分值
        buildCell(() => '${row.scoreValue}'),
        //折算后分数
        buildCell(() => '${row.scoreValue * row.discount}(${row.discount})'),
        //状态
        buildCell(() => appDictData.getLabel('status', row.status)),
        //创建时间
        buildCell(() => dateUtils.format(dtFormat, row.createdAt)),
        //操作
        DataCell(OverflowBar(
          spacing: 2.w,
          children: [
            //修改
            buttons.modify(onPressed: () {
              final id = row.id;
              if (id.isNotEmpty) {
                editHandler(model, id);
              }
            }),
            //删除
            buttons.delete(onPressed: () {
              final id = row.id;
              if (id.isNotEmpty) {
                model.onDeleteHandler(schoolId: widget.schoolId, id: id);
              }
            }),
          ],
        )),
      ],
    );
  }
}
